'use client';

import { useState, useEffect } from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { Button, Dialog, DialogTitle, DialogContent, DialogActions, TextField, IconButton, Stack } from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import DeleteIcon from '@mui/icons-material/Delete';
import { getQuestions } from '@/api/questions';
import { examApi } from '@/api/exams';

interface Question {
  id: number;
  subject: string;
  type: string;
  content: string;
  score: number;
  options?: string[];
  answer: string;
  explanation: string;
}

interface ExamQuestionsProps {
  examId: number;
  subject: string;
  onQuestionsChange: (questions: Question[]) => void;
  initialQuestions?: Question[];
}

export default function ExamQuestions({ examId, subject, onQuestionsChange, initialQuestions = [] }: ExamQuestionsProps) {
  const [questions, setQuestions] = useState<Question[]>(initialQuestions);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [availableQuestions, setAvailableQuestions] = useState<Question[]>([]);
  const [selectedQuestions, setSelectedQuestions] = useState<number[]>([]);
  const [randomCount, setRandomCount] = useState<string>('');

  useEffect(() => {
    // 获取题库中的题目
    const fetchQuestions = async () => {
      try {
        const data = await getQuestions();
        // 根据科目筛选题目
        const filteredQuestions = data.filter(q => q.subject === subject);
        setAvailableQuestions(filteredQuestions.map(q => ({
          ...q,
          id: q.id || Math.random(),
          type: q.type || 'UNKNOWN'
        })));
      } catch (error) {
        console.error('获取题目失败:', error);
        setAvailableQuestions([]);
      }
    };

    if (subject) {
      fetchQuestions();
    }
  }, [subject]);

  const handleAddQuestions = () => {
    setIsModalOpen(true);
  };

  const handleConfirmAdd = () => {
    if (selectedQuestions.length === 0) return;
    
    const existingIds = questions.map(q => q.id);
    const selectedQuestionsData = availableQuestions
      .filter(q => selectedQuestions.includes(q.id) && !existingIds.includes(q.id))
      .map(q => ({
        id: q.id,
        subject: q.subject,
        type: q.type,
        content: q.content,
        options: q.options,
        answer: q.answer,
        explanation: q.explanation,
        score: q.score
      }));

    const newQuestions = [...questions, ...selectedQuestionsData];
    setQuestions(newQuestions);
    onQuestionsChange(newQuestions);
    setIsModalOpen(false);
    setSelectedQuestions([]);
  };

  const handleRemoveQuestion = (questionId: number) => {
    const newQuestions = questions.filter(q => q.id !== questionId);
    setQuestions(newQuestions);
    onQuestionsChange(newQuestions);
  };

  const handleRandomQuestions = async () => {
    if (!randomCount || isNaN(Number(randomCount)) || Number(randomCount) <= 0) {
      alert('请输入有效的题目数量');
      return;
    }

    try {
      if (examId) {
        await examApi.generateQuestions(examId, {
          count: Number(randomCount),
          subject: subject
        });
        // 重新获取题目列表
        const data = await getQuestions();
        const filteredQuestions = data.filter(q => q.subject === subject);
        setAvailableQuestions(filteredQuestions);
      } else {
        // 如果是新建考试，直接从可用题目中随机选择
        const availableIds = availableQuestions.map(q => q.id);
        const randomIds = [];
        const count = Math.min(Number(randomCount), availableIds.length);
        
        while (randomIds.length < count) {
          const randomIndex = Math.floor(Math.random() * availableIds.length);
          const randomId = availableIds[randomIndex];
          if (!randomIds.includes(randomId)) {
            randomIds.push(randomId);
          }
        }

        const randomQuestions = availableQuestions.filter(q => randomIds.includes(q.id));
        setQuestions(randomQuestions);
        onQuestionsChange(randomQuestions);
      }

      setRandomCount('');
      setIsModalOpen(false);
    } catch (error) {
      console.error('随机抽题失败:', error);
      alert('随机抽题失败');
    }
  };

  const columns = [
    { field: 'content', headerName: '题目内容', flex: 1, headerAlign: 'center', align: 'center' },
    { field: 'type', headerName: '题目类型', width: 120, headerAlign: 'center', align: 'center' },
    { field: 'answer', headerName: '答案', width: 120, headerAlign: 'center', align: 'center' },
    { field: 'score', headerName: '分值', width: 120, headerAlign: 'center', align: 'center' },
    {
      field: 'actions',
      headerName: '操作',
      width: 100,
      headerAlign: 'center',
      align: 'center',
      renderCell: (params: any) => (
        <IconButton
          onClick={() => handleRemoveQuestion(params.row.id)}
          size="small"
          color="error"
        >
          <DeleteIcon />
        </IconButton>
      ),
    },
  ];

  const modalColumns = [
    { field: 'content', headerName: '题目内容', flex: 1, headerAlign: 'center', align: 'center' },
    { field: 'type', headerName: '题目类型', width: 120, headerAlign: 'center', align: 'center' },
    { field: 'answer', headerName: '答案', width: 120, headerAlign: 'center', align: 'center' },
    { field: 'score', headerName: '分值', width: 120, headerAlign: 'center', align: 'center' },
  ];

  return (
    <div className="mt-4">
      <div className="flex justify-between mb-4">
        <h2 className="text-lg font-semibold">考试题目</h2>
        <Stack direction="row" spacing={2}>
          <TextField
            size="small"
            label="随机抽题数量"
            type="number"
            value={randomCount}
            onChange={(e) => setRandomCount(e.target.value)}
            sx={{ width: 150 }}
          />
          <Button
            variant="outlined"
            onClick={handleRandomQuestions}
          >
            随机抽题
          </Button>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={handleAddQuestions}
          >
            添加题目
          </Button>
        </Stack>
      </div>

      <div style={{ height: 400 }}>
        <DataGrid
          rows={questions}
          columns={columns}
          pageSize={5}
          rowsPerPageOptions={[5]}
          disableSelectionOnClick
        />
      </div>

      <Dialog
        open={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>选择题目</DialogTitle>
        <DialogContent>
          <div style={{ height: 400, width: '100%' }}>
            <DataGrid
              rows={availableQuestions}
              columns={modalColumns}
              pageSize={5}
              rowsPerPageOptions={[5]}
              checkboxSelection
              rowSelectionModel={selectedQuestions}
              onRowSelectionModelChange={(newSelection) => {
                setSelectedQuestions(newSelection as number[]);
              }}
            />
          </div>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setIsModalOpen(false)}>取消</Button>
          <Button onClick={handleConfirmAdd} variant="contained" color="primary">
            确认添加
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}